
let { User, Message, Comment } = require("../models");
let auth = require('../utils/auth');


//说说界面
let tinytalk_fn = async (ctx, next) => {
    let username = ctx.session.userName;

    //查找所有說說內容
    let msgs = JSON.parse(JSON.stringify(await Message.findAll(
        {
            order: [
                ["id", "desc"]
            ],
        }
    )));
    let comts = JSON.parse(JSON.stringify(await Comment.findAll()));
    let userIds=[];

    // 谁对谁说功能 第一步查找到msg中所有的fromUserId
    msgs.forEach(row=>{
        userIds.push(row.fromUserId);
    });

    //谁对谁说功能 第二步查找到comts中所有的fromUserId
    comts.forEach(row=>{
        userIds.push(row.fromUserId);
    });

    //谁对谁说功能 第三步查根据找查到的用户Id，查找用户表中的用户信息

    let userAll=await User.findAll({
    
    })// select * from users where id in (1,2,3,4)

    console.log("userIds："+userIds);
    console.log("comts："+comts);

    for(let i=0; i<User.length;i++){
        console.log("userAll_Id"+User[i].id);
    }
   
    console.log("userAll："+userAll);
  
    // 
    comts.forEach(row=>{
        let currentUser=userAll.filter(user=>{
            console.log("1:"+row.fromUserId);
            console.log("2:"+user.id);

            return row.fromUserId===user.id;
        })[0];
        console.log(currentUser);
        row.comUserName=currentUser.username;
    });

    // 将说说和评论根据msgId按需要组合，将相应的评论挂载在对应的说说上
    msgs.forEach(msg=>{
        let msgComment=comts.filter(item=>{
            return item.msgId===msg.id;
        });
        let currentUser=userAll.filter(row=>{
            return row.id===msg.fromUserId;
        })[0];
        msg.msgUserName=currentUser.username;
        msg.comments=msgComment;
    });

    console.log(msgs);

    let obj={
        username:username,
        msgs:msgs
    };
    ctx.render('tinytalk.html',obj);
}

//登录界面
let login_fn = async (ctx, next) => {
    ctx.render('login.html');
}

//註銷后
let logout_fn = async (ctx, next) => {
    ctx.session = null;
    ctx.body = { code: 200, msg: '注销成功' };
}

//注册界面
let register_fn = async (ctx, next) => {
    ctx.render('register.html');
}

let loginDone_fn = async (ctx, next) => {
    let username = ctx.request.body.username || '';
    let password = ctx.request.body.password || '';

    console.log(username);

    let res;
    let u1 = await User.findOne({
        where: {
            username: username,
            password: password
        }
    }).then((row) => {
        let user = JSON.stringify(row);
        let u2 = JSON.parse(user);
        console.log(user);
        console.log(u2);

        if (user !== 'null') {
            ctx.session.userId = row.id;
            ctx.session.userName = row.username;
            res = { code: 200, msg: '登录成功' };
        } else {
            res = { code: 1000, msg: '用户名或密码错误，请重试' };
        }
    });
    ctx.body = res;
}

let registerDone_fn = async (ctx, next) => {
    let username = ctx.request.body.username || '';
    let password = ctx.request.body.password || '';
    let confirmpassword = ctx.request.body.confirmpassword || '';


    if (username.length > 0 && password.length > 0 && confirmpassword.length > 0 && confirmpassword === password) {
        //同名
        let userDemo = await User.findOne({ where: { username: username } });
        console.log(JSON.stringify(userDemo));
        //设置一个空字符串
        let res = '';
        if (userDemo) {
            res = { code: 1000, msg: '当前用户已注册' };
        } else {
            let u1 = User.create({
                username: username,
                password: password
            });
            res = { code: 200, msg: '注册成功，正在跳转到页面' };
        }
        ctx.body = JSON.stringify(res);

    } else {
        console.log('用户名或密码不能为空 ，两次密码应该相同');
    }
}

let say_fn = async (ctx, next) => {
    let msgSay = ctx.request.body.msgSay || '';
    let userId = ctx.session.userId;
    let msg1 = await Message.create({
        fromUserId: userId,
        content: msgSay
    });

    let data = JSON.stringify(msg1);

    console.log(msgSay);

    ctx.body = { code: 200, data, msg: '發表成功' };
}

//对谁说
let comment_fn = async (ctx, next) => {
    let msgId = ctx.request.body.msgId || '';
    let userId = ctx.session.userId;
    let commentText = ctx.request.body.content || '';


    console.log(msgId);
    console.log(userId);
    console.log(commentText);

    let msg1 = await Comment.create({
        fromUserId: userId,
        msgId: msgId,
        content: commentText
    });

    // 根据fromUsreId查询对应的用户名
    let fromUser=await User.findOne({
        where:{
            id:userId
        }
    });

    //根据msgId找到fromUserId
    let msg=await Message.findOne({
        where:{
            id:msgId
        }
    });

    //根据找到fromUserId，查找相对应的用户名
    let toUser=await User.findOne({
        where:{
            id:msg.fromUserId
        }
    });

    let data=JSON.parse(JSON.stringify(msg1));

    data.fromUserName=fromUser.username;
    data.toUserName=toUser.username;

    ctx.body = { code: 200, data, msg: '發表成功' };
}


let test_fn = async () => {
    let obj = {
        nickname: '999',
        age: 88
    }
    return JSON.stringify(obj);
}





module.exports = {
    '/': ['get', auth, tinytalk_fn],
    '/login': ['get', auth, login_fn],
    '/logout': ['post', logout_fn],
    '/register': ['get', register_fn],
    '/loginDone': ['post', loginDone_fn],
    '/registerDone': ['post', registerDone_fn],
    '/say': ['post', say_fn],
    '/comment': ['post', comment_fn],
    '/testDone': ['post', test_fn],
}